package com.cskaoyan.jdbc.crud;

import com.mysql.jdbc.Driver;

import java.sql.*;

/**
 * 创建日期: 2022/05/12 16:38
 *
 * @author ciggar
 */
public class QueryJDBCDemo {

    public static void main(String[] args) throws SQLException {


        // 1. 加载驱动  {@Link java.sql.Driver   impl : com.mysql.jdbc.Driver}
        DriverManager.registerDriver(new Driver());


//        String url = "协议 + ip + 端口 + 路径 + 参数";
        String url = "jdbc:mysql://localhost:3306/40th?useSSL=false&characterEncoding=utf8";
        String username = "root";
        String password = "123456";


        // 2. 发送用户名和密码，建立连接
        // 返回的当前是一个Connection接口，但是实际上在运行的时候，返回是Connection接口的实现类的实例
        // JDBC4Connection ，是java.sql.Connection 接口的实现类
        Connection connection = DriverManager.getConnection(url, username, password);


        // 3. 获取statement对象
        Statement statement = connection.createStatement();

        // 3. 发送SQL语句
        // resultSet指结果集对象，具体指代查询返回的临时表对象
        ResultSet resultSet = statement.executeQuery("select * from stu");


        // 4. 解析结果集
//        Boolean ret = resultSet.next();

//        if (ret) {
//
//            int id = resultSet.getInt("id");
//            String name = resultSet.getString("name");
//            int age = resultSet.getInt("age");
//            String className = resultSet.getString("class");
//
//            System.out.println("id:" + id);
//            System.out.println("name:" + name);
//            System.out.println("age:" + age);
//            System.out.println("className:" + className);
//        }

        while (resultSet.next()) {

            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            int age = resultSet.getInt("age");
            String className = resultSet.getString("class");

            System.out.println("id:" + id);
            System.out.println("name:" + name);
            System.out.println("age:" + age);
            System.out.println("className:" + className);

        }


        // 5. 断开连接
        resultSet.close();
        statement.close();
        connection.close();


    }
}
